#include "client.h"
#include <bits/fcntl-linux.h>
#define _GNU_SOURCE
#define __USE_GNU
int recvn(int sockFd, void *pstart, int len)
{
    int total = 0;
    int ret;
    char *p = (char *)pstart;
    while (total < len)
    {
        ret = recv(sockFd, p + total, len - total, 0);
        total += ret;
    }
    return 0;
}
int recvTask(int sockFd)
{
  
   // 先获取文件名
   char name[1024] = {0};
   int dataLength;
   char new_name[2048];
   // int ret = recv(sockFd,&dataLength,sizeof(int),MSG_WAITALL);
   int ret = recvn(sockFd, &dataLength, sizeof(int));
   ERROR_CHECK(ret, -1, "recv");
   // ret = recv(sockFd,name,dataLength,MSG_WAITALL);
   ret = recvn(sockFd, name, dataLength);
   puts(name);
   ERROR_CHECK(ret, -1, "recv");
   sprintf(new_name, "dest/%s", name);
   int fd = open(new_name, O_RDWR | O_CREAT | O_TRUNC, 0666);
   ERROR_CHECK(fd, -1, "open");
   int fileSize;
   recvn(sockFd, &dataLength, sizeof(int));
   recvn(sockFd, &fileSize, dataLength);
   printf("fileSize = %d\n", fileSize);
   char buf[1000] = {0};
   time_t timeBeg, timeEnd;
   timeBeg = time(NULL);

   //  int pipefds[2];
   //  pipe(pipefds);
   //  int total = 0;
   //  while(total < fileSize){
   //      int ret = splice(sockFd,NULL,pipefds[1],NULL,4096,SPLICE_F_MORE);
   //      total += ret;
   //      //usleep(2000000);
   //      splice(pipefds[0],NULL,fd,NULL,ret,SPLICE_F_MORE);
   //  }

   ftruncate(fd, fileSize);
   char *p = (char *)mmap(NULL, fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
   ERROR_CHECK(p, MAP_FAILED, "mmap");
   recvn(sockFd, p, fileSize);

   recvn(sockFd, &dataLength, sizeof(int));
   printf("dataLength = %d\n", dataLength);
   timeEnd = time(NULL);
   printf("total time = %ld\n", timeEnd - timeBeg);
}
